﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using AutoMapper;
using Ccteg.Common;
using Ccteg.DB;
using LinqKit;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Org.BouncyCastle.Asn1.Crmf;

namespace Cctegaq.Api.Controllers.Api
{
    /// <summary>
    /// 安全组织机构
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class ORGController : ControllerBase
    {
        private readonly IMapper _mapper;
        private readonly MySqlDbContext _dbContext;


        public ORGController(MySqlDbContext dbContext, IMapper mapper)
        {

            _dbContext = dbContext;
            _mapper = mapper;
        }
        /// <summary>
        /// 集团组织机构添加 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ResponseModel ORGORGOrUpdate([FromBody] Org_Org_ViewModel model)
        {
            var response = ResponseModelFactory.CreateInstance;
            try
            {
                using (_dbContext)
                {
                    model.CompanyNo = "001";

                    var entity = _mapper.Map<Org_Org_ViewModel, org_org>(model);
                    if (entity.Id > 0)
                    {
                        //如果修改 本节点为 parentid=0; 不能修改
                        var editentity = _dbContext.ORG_Org.AsNoTracking().Where(x => x.Id == entity.Id && x.Deleted == false && x.State == "1").AsNoTracking().FirstOrDefault();
                        if (editentity == null)
                        {
                            response.SetFailed("无法修改，数据不存在请刷新页面");
                            return response;
                        }
                        if (editentity.ParentOrgNo == "0" && entity.ParentOrgNo != "0")
                        {
                            response.SetFailed("根节点不能修改上级机构");
                            return response;
                        }
                        if (editentity.ParentOrgNo != "0" && entity.ParentOrgNo == "0")
                        {
                            response.SetFailed("根节点已存在请调整上级节点");
                            return response;
                        }
                        var modify_model = _dbContext.ModifyEntityValue(entity, x => new
                        {
                            x.Name,
                            x.NumOrder,
                            x.Header,
                            x.Tel,
                            x.Duty,
                            x.Remark,
                            x.ParentOrgNo
                        });
                        entity.ModifiedBy = "系统";
                        entity.ModifiedOn = System.DateTime.Now;
                        entity.CompanyName = "中国煤科";
                        entity.State = "1";

                        if (modify_model && _dbContext.SaveChanges() > 0)
                        {

                            org_org o = editentity;
                            o.Id = 0;
                            o.State = "0";
                            _dbContext.ORG_Org.Add(o);
                            _dbContext.SaveChanges();
                        }
                        else
                        {
                            response.SetFailed("操作失败");
                            return response;
                        }
                    }
                    else
                    {
                        if (entity.ParentOrgNo == "string")
                        {
                            response.SetFailed("请选择上级机构");
                            return response;
                        }
                        entity.OrgNo = "001_" + RandomHelper.GetRandomizer(8, true, false, false, true, true);
                        //无节点的情况 
                        if (!_dbContext.ORG_Org.Any(x => x.CompanyNo == "001" && x.State == "1" && x.Deleted == false))
                        {
                            entity.Id = 0;
                            entity.ParentOrgNo = "0";

                        }
                        else if (_dbContext.ORG_Org.Any(x => x.CompanyNo == "001" && x.ParentOrgNo == "0" && x.State == "1" && x.Deleted == false) && entity.ParentOrgNo == "0")
                        {
                            response.SetFailed("请选择上级机构");
                            return response;
                        }
                        var entryEntity = _dbContext.ORG_Org.Attach(entity);
                        entryEntity.Property(p => p.ModifiedBy).IsModified = false;
                        entryEntity.Property(p => p.ModifiedOn).IsModified = false;
                        entity.Deleted = false;
                        entity.CreatedBy = "系统";
                        entity.State = "1";
                        entity.CompanyName = "中国煤科";
                        entity.CreatedOn = System.DateTime.Now;
                        _dbContext.SaveChanges();
                    }

                    response.SetSuccess("操作成功");

                }
            }
            catch (Exception ex)
            {
                response.SetFailed("操作失败");
                response.Data = ex.Message;
            }
            return response;
        }
        private IEnumerable<Tree_ViewModel> GetClassID(string p_id, List<Tree_ViewModel> list)
        {
            var query = from c in list
                        where c.ParentId == p_id
                        select c;

            return query.ToList().Concat(query.ToList().SelectMany(t => GetClassID(t.Id, list)));
        }
        /// <summary>
        /// 集团组织机构删除
        /// </summary>
        /// <param name="OrgNo">机构编码</param>
        /// <returns></returns>
        [HttpPost]
        public ResponseModel ORGDelete([Required] string OrgNo)
        {
            var response = ResponseModelFactory.CreateInstance;
            try
            {
                using (_dbContext)

                {
                    var query = _dbContext.ORG_Org.AsNoTracking().Where(x => x.CompanyNo == "001" && x.State == "1" && x.Deleted == false);
                    var deletedata = query.Select(_mapper.Map<org_org, Tree_ViewModel>);
                    //子集
                    var treedelids = TreeHelper.BuildTreeForMatFrist(deletedata.ToList(), parentId: OrgNo);
                    treedelids.Add(new Tree_ViewModel { Id = OrgNo });

                    ////删除
                    var delres = (from p in _dbContext.ORG_Org
                                  where (treedelids.Select(x => x.Id)).Contains(p.OrgNo)
                                  select p)
                                     .SetField(x => x.Deleted).WithValue(false)
                                       .SetField(x => x.ModifiedOn).WithValue(DateTime.Now)
                                         .SetField(x => x.ModifiedBy).WithValue("系统")
                                     .Update();

                    response.SetData("操作成功");
                }
            }
            catch (Exception ex)
            {
                response.SetFailed("操作失败");
                response.Data = ex.Message;
            }
            return response;
        }


        /// <summary>
        /// 组织机构tree
        /// </summary>
        /// <param name="companyno">单位编码</param>

        /// <returns></returns>
        [HttpGet]
        public ResponseModel<Tree_ViewModel> ORGTreeSearch([Required] string companyno)
        {
            using (_dbContext)
            {

                var response = new ResponseModel<Tree_ViewModel>();
                Expression<Func<org_org, bool>> where = p => true;
                //根据单位编码过滤
                where = where.CheckNullAnd(x => x.CompanyNo == companyno, companyno).And(x => x.State == "1").And(x => x.Deleted == false);

                var query = _dbContext.ORG_Org.AsQueryable();

                query = query.Where(where.Expand()).OrderBy(x => x.Sort);
                var data = query.Select(_mapper.Map<org_org, Tree_ViewModel>);
                if (data.Any(x => x.ParentId == "0"))
                {
                    response.SetData(TreeHelper.BuildTree(data.ToList()).FirstOrDefault());
                }
                return response;
            }
        }
        /// <summary>
        /// 组织机构详情
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet]
        public ResponseModel<Org_Org_ViewModel> ORGDetail([Required] int id)
        {
            using (_dbContext)
            {

                var response = new ResponseModel<Org_Org_ViewModel>();
                var query = _dbContext.ORG_Org.AsNoTracking().Where(x => x.Id == id && x.Deleted == false).FirstOrDefault();
                var data = _mapper.Map<org_org, Org_Org_ViewModel>(query);
                response.SetData(data);
                return response;
            }

        }
    }

}
